package com.ndp.fb.walle.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.ndp.fb.rdb.api.EcElementCategoryRdbService;
import com.ndp.fb.rdb.model.EcElementCategory;
import com.ndp.fb.rdb.model.User;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Iterator;
import java.util.List;

/**
 * Created by jacky.cheng on 2016/5/31.
 */
@RestController
@RequestMapping("elementCategory")
public class EcElementCategoryController {
    @Reference
    private EcElementCategoryRdbService ecElementCategoryRdbService;

    @RequestMapping("all")
    List<EcElementCategory> findAll(HttpServletRequest req) {
        User user = (User) req.getSession().getAttribute("user");
        List<EcElementCategory> all = ecElementCategoryRdbService.findAll();
        EcElementCategory p = new EcElementCategory(0L);
        toTreeByPid(p, all);
        return p.getChildren();
    }

    @RequestMapping("allCreate")
    List<EcElementCategory> allCreate(HttpServletRequest req) {
        User user = (User) req.getSession().getAttribute("user");
        List<EcElementCategory> all = ecElementCategoryRdbService.allCreate();
        EcElementCategory p = new EcElementCategory(0L);
        toTreeByPid(p, all);
        return p.getChildren();
    }

    @RequestMapping("save")
    Long save(@RequestBody EcElementCategory param) {
        return ecElementCategoryRdbService.save(param);
    }

    @RequestMapping("update")
    void update(@RequestBody EcElementCategory param) {
        ecElementCategoryRdbService.update(param);
    }

    private void toTreeByPid(EcElementCategory p, List<EcElementCategory> all) {
        Iterator<EcElementCategory> iterator = all.iterator();
        while (iterator.hasNext()){
            EcElementCategory c = iterator.next();
            if (c.getPid().intValue() == 0){
                c.setName(c.getContext());
            }

            if (c.getPid().equals(p.getId())) {
                p.getChildren().add(c);
                iterator.remove();
            }
        }
        p.getChildren().forEach(i -> toTreeByPid(i, all));
    }
}
